package com.crpc.network.netty;

import com.crpc.common.CThreadFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetAddress;
import java.net.InetSocketAddress;

public class NettyServer {

    private InetSocketAddress socketAddress;

    public NettyServer() {

    }

    void doStart() throws Exception {

        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup bossLoop = new NioEventLoopGroup(1, CThreadFactory.create("BossLoop"));
        EventLoopGroup workerLoop = new NioEventLoopGroup(1,CThreadFactory.create("WorkerLoop"));

        bootstrap.group(bossLoop,workerLoop);

        bootstrap.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("encode",new TestChannelHandler());
            }
        });


        socketAddress = new InetSocketAddress(InetAddress.getLocalHost(),10000);
        ChannelFuture channelFuture = bootstrap.bind(socketAddress);
        channelFuture.channel().closeFuture().sync();
    }

    public static void main(String[] args) {
        NettyServer nettyServer = new NettyServer();

        try {
            nettyServer.doStart();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class TestChannelHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("收到消息类型" + msg.getClass().getName());
            System.out.println("收到消息: " + msg);
        }
    }
}
